<template>
  <div>
    <h2>新增教师</h2>
    <el-form ref="form" :model="teacher" :rules="rules" label-width="100px" style="max-width: 500px; margin: 0 auto;">
      <el-form-item label="姓名" prop="sname">
        <el-input v-model="teacher.tname" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="年龄" prop="sage">
        <el-input v-model.number="teacher.tage" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="ssex">
        <el-radio-group v-model="teacher.tsex">
          <el-radio label="男">男</el-radio>
          <el-radio label="女">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="cancelAdd">取消</el-button>
      </el-form-item>
    </el-form>

  </div>
</template>

<script>
import axios from 'axios';
export default {
  name: 'AddTeacher',
  props:["dialogVisible"],
  data() {
    return {
     
      visible: false,
      teacher: {
        tname: '',
        tage: '',
        tsex: '男'
      },
      rules: {
        tname: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        tage: [
          { required: true, message: '请输入年龄', trigger: 'blur' },
          { type: 'number', min: 1, max: 100, message: '年龄必须是1-100之间的数字', trigger: 'blur' }
        ],
        tsex: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true;
          axios
            .post(`/addTeacher`, this.teacher)
            .then(() => {
              this.$message.success('添加成功');
              this.loading = false;
              this.$emit('closeDialog',true);
            })
            .catch((error) => {
              this.$message.error(`添加失败：${error.message}`);
              this.loading = false;
              this.$emit('closeDialog',false);
            });
        } else {
          return false;
        }
      });
      this.$refs.form.resetFields();

      
    },
    cancelAdd() {
      this.$refs.form.resetFields();// 取消添加后，重置表单数据
      this.$emit('closeDialog',false);
    }
  }
}
</script>
